package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.CreditManager;
import com.anne.fish.model.Credit;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class CreditAction extends BaseAction implements Preparable {
    private CreditManager creditManager;
    private List credits;
    private Credit credit;
    private Long id;
    private String query;

    public void setCreditManager(CreditManager creditManager) {
        this.creditManager = creditManager;
    }

    public List getCredits() {
        return credits;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String creditId = getRequest().getParameter("credit.id");
            if (creditId != null && !creditId.equals("")) {
                credit = creditManager.get(new Long(creditId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        credits = creditManager.search(query, Credit.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Credit getCredit() {
        return credit;
    }

    public void setCredit(Credit credit) {
        this.credit = credit;
    }

    public String delete() {
        creditManager.remove(credit.getId());
        saveMessage(getText("credit.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            credit = creditManager.get(id);
        } else {
            credit = new Credit();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (credit.getId() == null);

        creditManager.save(credit);

        String key = (isNew) ? "credit.added" : "credit.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}